package net.test.piggy.controller;


import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Controller
@Api(tags = "RabbitController")
public class RabbitController {
    Logger logger = LoggerFactory.getLogger(RabbitController.class);
    @Resource
    private RabbitTemplate rabbitTemplate;

    @ResponseBody
    @GetMapping("rabbit01")
    public String rabbit01() {
        rabbitTemplate.convertAndSend("ttl.exchange", "ttl_key", "rabbit01", message -> {
            // rabbitMQ 消息队列中前一个消息不发送，会造成后续消息阻塞，时间到期也不会发送
            // message.getMessageProperties().setExpiration("180000");
            return message;
        });
        return "@rabbit01";
    }
    @ResponseBody
    @GetMapping("rabbit02")
    @ApiImplicitParams({
            @ApiImplicitParam(name="message",value="消息",required=true),
    })
    @ApiOperation(value = "方法作用", notes = "备注说明")
    public String sendDirectMessage(String message) {
        String messageId = UUID.randomUUID().toString();
        String messageData = UUID.randomUUID().toString();;
        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("messageId",messageId);
        jsonObject.put("messageData",messageData+":"+message);
        jsonObject.put("createTime",createTime);
        String string = jsonObject.toString();
        rabbitTemplate.convertAndSend("piggy.direct.exchange", "piggy_key", string);
        rabbitTemplate.convertAndSend("piggy.direct.exchange", "temp_key", string);
        rabbitTemplate.convertAndSend("piggy.ttl.exchange", "ttl_key", string);
        return "SuccessSendMessageToQueue";
    }

    @RabbitListener(queues = "piggy-direct-queue")
    public void receiveMessage(String string){
        logger.info(" receive piggy-direct-queue message --> {}",string);
    }
}
